import logging
import unittest

from api.home_api import HomeApi
from common.db_util import DBUtil
import config.db_cnf as db_cnf
import config.params_cnf as params_cnf


class TestHome(unittest.TestCase):
    dbUtil = None

    @classmethod
    def setUp(cls) -> None:
        cls.dbUtil = DBUtil(host=db_cnf.host, port=db_cnf.port,
                            user=db_cnf.user, password=db_cnf.password,
                            database=db_cnf.database)

    def test_banner(self):
        print('轮播图')

        # 将请求的断言置前，为了处理异常场景：后台查询不到值，返回500错误
        # 断言失败时，抛出异常，不执行后续代码
        resp = HomeApi().get_banner(params_cnf.BANNER_ID)
        self.assertEqual(200, resp.status_code)

        # 预期结果：数据库轮播图个数
        sql = f"SELECT count(*) FROM banner_item WHERE banner_id = '{params_cnf.BANNER_ID}'"
        db_data = self.dbUtil.dql_one(sql)[0]
        logging.info(db_data)

        self.assertEqual(db_data, len(resp.json().get('items')))

    def test_theme(self):
        print('专题栏位')

        resp = HomeApi().get_theme(params_cnf.THEME_LIST)
        self.assertEqual(200, resp.status_code)

        # 预期结果：数据库中专题栏位个数
        sql = f"SELECT count(*) FROM theme WHERE id IN ({params_cnf.THEME_LIST})"
        db_data = self.dbUtil.dql_one(sql)[0]
        logging.info(db_data)

        self.assertTrue(len(resp.json()) > 0)
        self.assertEqual(db_data, len(resp.json()))

    def test_recent_product(self):
        # 最近新品为数据库product表前15条的数据
        print('最近新品')

        resp = HomeApi().get_recent_product()
        self.assertEqual(200, resp.status_code)

        # 预期结果：数据库product表第一条数据
        sql = "SELECT * FROM product LIMIT 0,1"
        db_data = self.dbUtil.dql_one(sql)[1]
        logging.info(db_data)

        resp_name = resp.json()[0].get('name')
        logging.info(resp_name)

        self.assertEqual(db_data, resp_name)
